package br.com.locanet.service.impl;

import javax.persistence.PersistenceException;

import br.com.locanet.bean.impl.Cliente;
import br.com.locanet.dao.database.impl.ClienteDAO;
import br.com.locanet.exception.ExceptionList;
import br.com.locanet.exception.InvalidAttributeException;

public class ClienteService extends AbstractPessoaService<Cliente, ClienteDAO> {
	@Override
	public void doValidateRequiredFields(Cliente entity) throws ExceptionList {
		ExceptionList fieldsInvalidos = new ExceptionList();
		try {
			super.doValidateRequiredFields(entity);
		} catch (ExceptionList e) {
				fieldsInvalidos.getListaErros().addAll(e.getListaErros());
		}
		if (entity.getEndereco() == null || entity.getEndereco().isEmpty())
			fieldsInvalidos.add(new InvalidAttributeException(
					"enderecoInvalido"));
		if (entity.getCep() == null || entity.getCep().isEmpty())
			fieldsInvalidos.add(new InvalidAttributeException(
					"cepInvalido"));
		/*CPFValidation cpfValidation = new CPFValidation(entity.getCpf());
		if (!cpfValidation.isValid())
			fieldsInvalidos.add(new InvalidAttributeException(
					"cpfInvalido"));*/
		if (entity.getTelefone_res() == null || entity.getTelefone_res().isEmpty())
			fieldsInvalidos.add(new InvalidAttributeException(
					"telefoneResNaoInformado"));
		if (!fieldsInvalidos.getListaErros().isEmpty())
			throw fieldsInvalidos;
	}

	@Override
	public void doValidateBusinessRules(Cliente entity) throws PersistenceException, ExceptionList{
		ExceptionList exceptionList = new ExceptionList();
		
		try{
			super.doValidateBusinessRules(entity);
		}catch(Exception e){
			throw new PersistenceException(e);
		}
		
		Cliente cliente = new Cliente();
		cliente.setId(entity.getId());
		cliente.setLogin(entity.getLogin());
		
		validaRepeticaoLogin(cliente, exceptionList);
		
		if (!exceptionList.getListaErros().isEmpty()) throw exceptionList;
	}
	@Override
	protected Cliente doMerge(Cliente entity) throws PersistenceException {
		Cliente oldEntity = super.doMerge(entity);

		if (entity.getCpf()!=null)
			oldEntity.setCpf(entity.getCpf());
		if (entity.getCep()!=null)
			oldEntity.setCep(entity.getCep());
		if (entity.getEndereco()!=null)
			oldEntity.setEndereco(entity.getEndereco());
		if (entity.getTelefone_cel()!=null)
			oldEntity.setTelefone_cel(entity.getTelefone_cel());
		if (entity.getTelefone_res()!=null)
			oldEntity.setTelefone_res(entity.getTelefone_res());
			
		return oldEntity;
	}
}
